package com.onpositive.wiki3.db.impl;

import java.io.BufferedOutputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.HashMap;

import com.carrotsearch.hppc.IntOpenHashSet;
import com.onpositive.wiki2.whole.model.ITemplateAccess;


public class TemplateStorage implements Serializable,ITemplateAccess{

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	protected String[]names;
	
	protected int[][] ids;
	
	public void write(String file) throws FileNotFoundException, IOException{
		ObjectOutputStream ss=new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(file)));
		ss.writeObject(this);
		ss.close();
	}

	@Override
	public int getMajorTemplateCount() {
		return names.length;
	}

	@Override
	public String getTemplateName(int num) {
		return names[num];
	}

	@Override
	public int[] getPages(int num) {
		return ids[num];
	}
	
	HashMap<Integer, IntOpenHashSet>maps;

	@Override
	public String[] getTemplates(int num) {
		builMaps();
		IntOpenHashSet intOpenHashSet = maps.get(num);
		if (intOpenHashSet==null){
			return new String[0];
		}
		String[] ss=new String[intOpenHashSet.size()];
		int i=0;
		for (int a:intOpenHashSet.toArray()){
			ss[i++]=names[a];
		}
		return ss;
	}
	


	protected void builMaps() {
		if (maps==null){
			maps=new HashMap<Integer, IntOpenHashSet>();
			for (int a=0;a<names.length;a++){
				int[] is = ids[a];
				for (int i:is){
					IntOpenHashSet intOpenHashSet = maps.get(i);
					if (intOpenHashSet==null){
						intOpenHashSet=new IntOpenHashSet();
						maps.put(i, intOpenHashSet);
					}
					intOpenHashSet.add(a);
				}
			}
		}
	}

	@Override
	public int getTemplateNum(String s) {
		int a=0;
		for (String sa:names){
			if (sa.equals(s)){
				return a;
			}
			a++;
		}
		return -1;
	}
}
